package com.ifinc.common.socket.simple_netty_client;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-5-30
 * Time: 00:46
 */

import com.ifinc.common.socket.client.ClientMessageDecoder;
import com.ifinc.common.socket.client.ClientMessageEncoder;
import com.ifinc.common.socket.client.ClientMessageHandler;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.logging.LoggingHandler;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.logging.Log4JLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


public class SimpleClientMessageFactory implements ChannelPipelineFactory {

    /**
     * 消息解码器
     */
    private ChannelHandler messageDecoder = new ClientMessageDecoder(Integer.MAX_VALUE, 0, 4, 0, 4);

    /**
     * 消息编码器
     */
    private ChannelHandler messageEncoder = new ClientMessageEncoder(4);

    /**
     * 消息分发的字节流处理器
     */
    private SimpleClientMessageHandler clientMessageHandler;

    @Autowired
    public void setClientMessageHandler(SimpleClientMessageHandler clientMessageHandler) {
        this.clientMessageHandler = clientMessageHandler;
    }

    public ChannelPipeline getPipeline() throws Exception {

        ChannelPipeline cp = Channels.pipeline();
               InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory());
        cp.addLast("logging", new LoggingHandler());

		cp.addLast("messageDecoder", messageDecoder);
		cp.addLast("messageEncoder", messageEncoder);
		cp.addLast("messageHandler", clientMessageHandler);

        return cp;
    }

    public SimpleClientMessageHandler getClientMessageHandler() {
        return clientMessageHandler;
    }
}